package com.biubiushop.socket.bio;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.List;

/**
 * TCP短连接客户端示例
 * @author chenjia
 * @date 2019/7/16
 **/
public class SocketClient {

    private static final Log log = LogFactory.get();

    public static void main(String[] args) throws Exception {
        Socket socket = new Socket("localhost",9999);
        OutputStream os = socket.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os);
        BufferedWriter bw = new BufferedWriter(osw);
        JSONObject jsonObject = new JSONObject();
        List<String> list = CollUtil.newArrayList();
        list.add("ssda");
        list.add(",.p;,pok");
        jsonObject.put("key1",1);
        jsonObject.put("key2",list);

        bw.write(jsonObject.toString());
        bw.flush();
        socket.shutdownOutput();

        System.out.println("======客户端读取服务端响应信息开始=======");
        InputStream is = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        String info = null;
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
            if (len < 1024) {
                info = baos.toString("gbk");
                log.info("客户端接收到服务器的响应信息:" + info);
                break;
            }
        }
        socket.shutdownInput();

        baos.close();
        is.close();

        bw.close();
        osw.close();
        os.close();
        socket.close();
    }

}
